// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

const rp = require('request-promise')

const URL = 'http://v3.wufazhuce.com:8000/api/channel/one/0/0'

const onelistCollection = db.collection('onelist')

const MAX_LIMIT = 100

// 云函数入口函数
exports.main = async (event, context) => {

  const countResult = await onelistCollection.count()
  const total = countResult.total
  const batchTimes = Math.ceil(total / MAX_LIMIT)
  let tasks = []
  for (let i = 0; i < batchTimes; i++) {
    const promise = onelistCollection.skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()
    tasks.push(promise)
  }
  let list = {
    data: []
  }
  if (tasks.length > 0) {
    list = (await Promise.all(tasks)).reduce((acc, cur) => {
      return {
        data: acc.data.concat(cur.data),
        errMsg: acc.errMsg,
      }
    })
  }

  const oneData = await rp(URL).then(res => {
    return JSON.parse(res).data
  })


  let newData = ''
  if (list.data.length > 0) {
    for (let i = 0, len = list.data.length; i < len; i++) {
      let flag = true
      console.log('kkkkkkkkkk', list.data[i].data.id, oneData.id)
      if (list.data[i].data.id == oneData.id) {
        flag = false
        newData = ''
        break
      }
      if (flag) {
        newData = oneData
      }
    }
  } else {
    newData = oneData
  }
  
  // // 插入数据库
  if (newData) {
    await onelistCollection.add({
      data: {
        data: newData,
        createTime: db.serverDate()
      }
    }).then(res => {
      console.log('插入成功')
    }).catch(err => {
      console.log('插入失败', err)
    })
  }

  return newData.length

}